package com.ruoyi.common.utils.excl.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.afterturn.easypoi.exception.excel.ExcelExportException;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.excl.export.CustomExcelExportStylerDefaultImpl;
import com.ruoyi.common.utils.excl.export.CustomExportService;
import com.ruoyi.common.utils.excl.model.ExcelCreateModel;
import com.ruoyi.common.utils.excl.workbook.CellStyleStrategy;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * Excel导入导出工具类
 *
 * @author laoz
 */
public class ExcelUtils
{

    /**
     * 从excel文件中读取多张sheet的值
     */
    public static <T> Map<String, List<T>> importExcelMultiple(MultipartFile file, Class<T> pojoClass, ImportParams params)
    {
        params.setTitleRows(1);
        params.setHeadRows(1);
        return baseImportExcelMultiple(file, pojoClass, params);
    }

    /**
     * 从excel文件中读取多张sheet的值
     */
    public static <T> Map<String, List<T>> baseImportExcelMultiple(MultipartFile file, Class<T> pojoClass, ImportParams params)
    {
        try {
            return new CExcelImportService().importExcelMultiple(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            throw new GlobalException("Excel表格数据读取失败");
        }
    }

    /**
     * 创建excel的workbook实体类
     * <p>
     * cn.afterturn.easypoi.excel.export.ExcelExportService#insertDataToSheet(org.apache.poi.ss.usermodel.Workbook, cn.afterturn.easypoi.excel.entity.ExportParams, java.util.List, java.util.Collection, org.apache.poi.ss.usermodel.Sheet)
     * 方法中 its.remove(); 每设置一行数值会删除列表中的信息，所以这里不能使用常量进行初始化复制
     * </p>
     *
     * @param modelList 模型列表
     */
    public static Workbook createExcelWorkbookMultipleSheet(List<ExcelCreateModel> modelList)
    {
        Workbook workbook = new HSSFWorkbook();
        ExcelExportService excelExportService = new ExcelExportService();
        for (ExcelCreateModel model : modelList) {
            excelExportService.createSheet(workbook,
                    new ExportParams(model.getTitle(), model.getSheetName()), model.getPojoClass(), model.getList());
        }
        return workbook;
    }

    /**
     * 创建excel的workbook实体类
     *
     * @param model 模型
     * @return workbook模型
     */
    public static Workbook createExcelWorkbookSheet(ExcelCreateModel model)
    {
        Workbook workbook = new HSSFWorkbook();
        ExcelExportService excelExportService = new ExcelExportService();
        excelExportService.createSheet(workbook,
                new ExportParams(model.getTitle(), model.getSheetName()), model.getPojoClass(), model.getList());
        return workbook;
    }

    /**
     * 创建excel的workbook实体类，支持数字版本
     *
     * @param model 模型
     * @return workbook模型
     */
    public static Workbook createExcelWorkbookSheetNumber(ExcelCreateModel model)
    {
        Workbook workbook = new HSSFWorkbook();
        CustomExportService customExportService = new CustomExportService();
        ExportParams exportParams = new ExportParams(model.getTitle(), model.getSheetName());
        exportParams.setStyle(CustomExcelExportStylerDefaultImpl.class);
        customExportService.createSheet(workbook, exportParams, model.getPojoClass(), model.getList());
        return workbook;
    }

    /**
     * 创建excel的workbook实体类
     *
     * @param list      数据列表
     * @param title     表格标题
     * @param sheetName 子表名称
     * @param pojoClass 实体类类型
     * @return excel的workbook实体类
     */
    public static Workbook createExcelWorkbook(List<?> list, String title, String sheetName, Class<?> pojoClass)
    {
        return ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, list);
    }

    public static CellStyle createCellStyle(Workbook workbook, List<CellStyleStrategy> cellStyleStrategyList) {
        CellStyle cellStyle = workbook.createCellStyle();
        Iterator<CellStyleStrategy> iterator = cellStyleStrategyList.iterator();
        while (iterator.hasNext()) {
            CellStyleStrategy cellStyleStrategy = iterator.next();
            cellStyleStrategy.setTemplateCellStyle(workbook, cellStyle);
        }
        return cellStyle;
    }

    public static void setSheetDefaultColumnStyle(Sheet sheet, CellStyle cellStyle, int columnNums) {
        for (int j = 0; j < columnNums; j++) {
            sheet.setDefaultColumnStyle(j, cellStyle);
        }
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response)
    {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response)
    {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
    {
        defaultExport(list, fileName, response);
    }

    public static void exportMultiSheet(String fileName, HttpServletResponse response, Workbook workbook)
    {
        downLoadExcel(fileName, response, workbook);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams)
    {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName,
                response,
                workbook);
    }

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
    {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new ExcelExportException(e.getMessage());
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
    {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) return;
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass)
    {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new ExcelExportException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExcelExportException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)
    {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new ExcelExportException("excel文件不能为空");
        } catch (Exception e) {
            throw new ExcelExportException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass, Integer keyIndex)
    {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass, keyIndex);
        } catch (Exception e) {
            throw new GlobalException("文件读取失败");
        }
    }

    public static <T> List<T> importExcel(InputStream inputstream, Integer titleRows, Integer headerRows, Class<T> pojoClass, Integer keyIndex)
    {
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setKeyIndex(keyIndex);
        List<T> list;
        try {
            list = ExcelImportUtil.importExcel(inputstream, pojoClass, params);
        } catch (Exception e) {
            throw new GlobalException("文件读取失败");
        }
        return list;
    }

    public static <T> List<T> importExcel(InputStream inputstream, Class<T> pojoClass, Integer keyIndex)
    {
        return importExcel(inputstream, 1, 1, pojoClass, keyIndex);
    }
}
